<script setup>
import LteCard from "../../../layout/components/LteCard.vue";
import LteGrid from "../../../layout/components/LteGrid.vue";
import LteGridForm from "../../../layout/global/LteGridForm";
import LteGridShow from "../../../layout/global/LteGridShow";
import LteModalAlert from "../../../layout/global/LteModalAlert";
import { reactive, onMounted, getCurrentInstance } from "vue";
import { GetUsers, Register, UpdateUser, DeleteUser, UpdateUserRoles } from "../../../apis/system/user";
import { checkPermissions } from "../../../modules/permission";
import userColumns from "./configs/userColumns";
import userRules from "./configs/userRules";
import registerColumns from "./configs/registerColumns";
import registerRules from "./configs/registerRules";
import UsersRoles from "./UsersRoles.vue";

const instance = getCurrentInstance();

const data = reactive({
    models: [],
    loading: false,
    pageSize: 20,
    pageCount: 0,
    pageNumber: 1,
    searchKey: '',
    searchInput: '',
});

const actions = [
    {
        title: "详情",
        class: "btn-info",
        action: function(model){
            const settings = {
                title: "详情",
                size: "sm",
                columns: userColumns,
                items: ["id", "username", "name", "state", "remark", 'created_at', 'updated_at'],
            };
            LteGridShow.open(settings, model);
        }
    },
    {
        title: "角色",
        class: "btn-warning",
        show: function(model){
            return !model.is_system && checkPermissions(["system_users_roles"]);
        },
        action: function(model){
            instance.refs.refRoles.open(model, function(record){
                UpdateUserRoles({id: model.id, role_ids: record}).then((res) => {
                    //关闭窗口
                    instance.refs.refRoles.close();
                }).catch((res) => {
                    //执行回调
                    instance.refs.refRoles.error(`修改失败: ${ res?.data?.message || '未知错误'}`);
                });
            });
        }
    },
    {
        title: "编辑",
        class: "btn-success",
        show: function(model){
            return !model.is_system && checkPermissions(["system_users_update"]);
        },
        action: function(model){
            const settings = {
                title: "编辑",
                size: "sm",
                columns: userColumns,
                rules: userRules,
                items: ["name", "state", "remark"],
            };
            LteGridForm.open(settings, model, function(record){
                UpdateUser(record).then((res) => {
                    for(let key in record) {
                        model[key] = record[key]
                    }
                    LteGridForm.close();
                }).catch((res) => {
                    LteGridForm.error(`修改失败: ${ res?.data?.message || '未知错误'}`);
                });
            });
        }
    },
    {
        title: "删除",
        class: "btn-danger",
        confirm: {
            type: "danger",
            title: "提示",
            message: "确认删除?",
        },
        show: function(model){
            return !model.is_system && checkPermissions(["system_users_delete"]);
        },
        action: function(model){
            DeleteUser({id: model.id}).then((res) => {
                load();
            }).catch((res) => {
                LteModalAlert.open({
                    modalSize: "sm",
                    type: 'danger',
                    title: '提示',
                    message: `删除失败: ${ res?.data?.message || '未知错误'}`,
                })
            });
        }
    },
];

const load = function(e) {
    data.loading = true;
    GetUsers({
        _page_size: data.pageSize,
        _page_number: data.pageNumber,
        _search_keyword: data.searchKey ? data.searchKey : undefined,
    }).then((res) => {
        data.models = res.data.result.list;
        data.pageSize = res.data.result.page_size;
        data.pageCount = res.data.result.page_count;
        data.pageNumber = res.data.result.page_number;
    }).finally((res) => {
        data.loading = false;
    });
};

const create = function(e) {
    const settings = {
        title: "添加",
        size: "sm",
        columns: registerColumns,
        rules: registerRules,
        items: ["username", "name", "password", "password_confirm"],
    };
    LteGridForm.open(settings, {}, function(record){
        //检测数据
        if(record.password !== record.password_confirm){
            LteGridForm.error("两次输入的密码不一致");
            return;
        }
        //执行注册
        Register(record).then((res) => {
            load();
            LteGridForm.close();
        }).catch((res) => {
            LteGridForm.error(res?.data?.message || "添加失败");
        })
    });
};

const search = function(e) {
    data.searchKey = data.searchInput;
    load();
};

const pageChange = function(e) {
    data.pageSize = e.pageSize;
    data.pageNumber = e.pageNumber;
    load();
};

onMounted(() => {
    load();
});
</script>

<template>
    <!-- 主内容 -->
    <lte-card title="列表" icon="fas fa-list" collapse maximize>
        <!-- 功能 -->
        <div class="row">
            <div class="col-sm">
                <div class="btn-group btn-group-sm">
                    <button type="button" class="btn btn-primary" @click="create" v-if="checkPermissions(['system_users_create'])"><i class="fa fa-plus"></i> 添加</button>
                    <button type="button" class="btn btn-info" @click="load"><i class="fa fa-undo"></i> 刷新</button>
                </div>
            </div>
            <div class="col-sm">
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" placeholder="search..." v-model="data.searchInput" @keyup.enter="search">
                    <span class="input-group-append">
                        <button type="button" class="btn btn-primary btn-flat" @click="search"><i class="fa fa-search"></i></button>
                    </span>
                </div>
            </div>
        </div>
        <!-- 表格 -->
        <lte-grid
            theme="element"
            :items="['id', 'username', 'name', 'state', 'created_at', 'updated_at']"
            :actions="actions"
            :columns="userColumns"
            :rows="data.models"
            :paginate-size="data.pageSize"
            :paginate-total="data.pageCount"
            :paginate-number="data.pageNumber"
            :loading="data.loading"
            @page-change="pageChange"
        >
        </lte-grid>
    </lte-card>
    <!-- 子页面 -->
    <users-roles ref="refRoles" ></users-roles>
</template>